package com.westa.smallshop.common;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;


import com.westa.smallshop.R;
import com.westa.smallshop.widget.ScrollChildSwipeRefreshLayout;

import butterknife.BindView;

/**
 * Created by Dune on 16/8/8.
 */
public abstract class BaseDetailFragment<P>
        extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseDetailView<P>, LoadDataInterface {

    @BindView(R.id.refresh_layout)
    ScrollChildSwipeRefreshLayout refreshLayout;
    @BindView(R.id.nested_scroll_view)
    NestedScrollView nestedScrollView;

    private long mLastLoadTime = 0;

    @Override
    public void loadingData(@DelayTime int delayTime) {

        long time = System.currentTimeMillis();
        switch (delayTime) {
            case DELAYED:
            case LOADING:
                if (time - mLastLoadTime > getResources().getInteger(R.integer.refresh_cycle)) {
                    new Handler().postDelayed(
                            new Runnable() {
                                @Override
                                public void run() {
                                    setRefreshing(true);
                                }
                            }, delayTime);
                    mLastLoadTime = time;
                }
                break;
            case IMMEDIATELY:
                setRefreshing(true);
                break;
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public final void initView() {

        refreshLayout.setColorSchemeResources(R.color.colorDominant);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setScrollUpChild(nestedScrollView);
        init();
    }


    @Override
    public void setRefreshLayoutEnabled(boolean isEnabled) {

        refreshLayout.setEnabled(isEnabled);
    }

    @Override
    public void setRefreshing(boolean isRefreshing) {

        refreshLayout.setRefreshing(isRefreshing);
        if (isRefreshing) {
            refreshData();
        }
    }

    @Override
    public void showEmptyView() {

    }

    @Override
    public void onRefresh() {

        refreshData();
    }

    @Override
    public boolean isActive() {
        return isAdded() && !isHidden();
    }

    public abstract void init();

    public abstract void refreshData();

}
